// ==========================================================================
// 所属模块：SysRole
// 生成日期：2024-03-24 16:10:31 +0800 CST
// 生成路径: /role/list/function.js
// 生成人：xScript_Engine
// 数据表：sys_roles - 角色表
// ==========================================================================

TABLE_NAME = 'sys_roles';
COLUMN_KEY = 'role_id';
TABLE_FIELDS = '*';
var selectDetailValue = 'role_id,role_name,status,role_key,data_scope,role_sort,update_by,remark';

'use api/lib/sql.js';

function getPlaceholders(condition) {
	const columnsArr = Object.keys(condition);
	const placeholders = [];
	const tempParams = [];
	columnsArr.forEach((item) => {
		if (item == 'roleName') {
			placeholders.push(`role_name LIKE ?`);
			tempParams.push('%' + condition[item] + '%');
		} else if (item == 'roleKey') {
			placeholders.push(`role_key LIKE ?`);
			tempParams.push('%' + condition[item] + '%');
		} else if (item == 'status') {
			placeholders.push(`status = ?`);
			tempParams.push(condition[item]);
		}
	});

	return {
		placeholders: placeholders.join(' AND '),
		tempParams: tempParams,
	};
}

function update() {
	const data = payload.get().body.toObject();
	const newData = {};
	Object.keys(data).forEach((item) => {
		newData[camelToUnderscore(item)] = data[item];
	});
	let filter = payload.get().path.split('/').pop();
	const columnsArr = Object.keys(newData);
	let dataArr = [];
	const placeholders = [];
	columnsArr.forEach((item) => {
		if (newData[item] && item != 'menu_ids' && item != 'api_ids') {
			placeholders.push(`${item} = ?`);
			dataArr.push(newData[item]);
		} else if (!newData[item]) {
			placeholders.push(`${item} = NULL`);
		}
	});
	const newPlaceholders = placeholders.join(',');
	// 更新role表
	const query = `UPDATE sys_roles SET ${newPlaceholders}, update_time = NOW() WHERE role_id = ?`;
	const res = SQL.exec('system_sql', query, ...[...dataArr, filter]);
	let menuRes = true;
	let apiRes = true;
	// 更新role_menu表
	if (newData.menu_ids.length && res) {
		let delRes;
		const delPre = SQL.query('system_sql', 'SELECT role_id FROM sys_role_menus_rel WHERE role_id = ?', filter);
		if (delPre.length) {
			delRes = SQL.exec('system_sql', 'DELETE FROM sys_role_menus_rel WHERE role_id = ?', filter);
		}
		let valueStrArr = [];
		const valueArr = [];
		for (let i = 0; i < newData.menu_ids.length; i++) {
			valueStrArr.push(`(?,?,?)`);
			valueArr.push(ex.suid().base58(), filter, newData.menu_ids[i]);
		}
		menuRes = SQL.exec('system_sql', `INSERT INTO sys_role_menus_rel (rule_id, role_id, menu_id) VALUES ${valueStrArr.join(',')}`, ...valueArr);
	}
	// 更新api权限相关表
	if (newData.api_ids.length && res) {
		SQL.exec('system_sql', 'DELETE FROM casbin_rule WHERE role_id = ?', newData.role_id);
		let valueStrArr = [];
		const valueArr = [];
		for (let i = 0; i < newData.api_ids.length; i++) {
			valueStrArr.push(`(?,?,?,?,?)`);
			valueArr.push(ex.suid().base58(), newData.role_id, newData.role_key, newData.api_ids[i].method, newData.api_ids[i].path);
		}
		apiRes = SQL.exec('system_sql', `INSERT INTO casbin_rule (rule_id, role_id, role_key, method, patterns) VALUES ${valueStrArr.join(',')};`, ...valueArr);
	}

	if (res && menuRes && apiRes) {
		return okMsg(res);
	}
	return errMsg(507, '更新失败');
}

function insert() {
	const data = payload.get().body.toObject();
	const newData = {};
	Object.keys(data).forEach((item) => {
		newData[camelToUnderscore(item)] = data[item];
	});
	const columnsArr = Object.keys(newData);
	let dataArr = Object.values(newData);
	const placeholders = ['?'];
	const newColumnsArr = ['role_id'];
	const newDataArr = [ex.suid().base58()];
	columnsArr.forEach((item) => {
		if (item != 'menu_ids' && item != 'api_ids') {
			newColumnsArr.push(item);
			placeholders.push('?');
			newDataArr.push(newData[item]);
		}
	});

	placeholders.join(',');
	const columnsStr = newColumnsArr.join(',');
	const query = `INSERT INTO sys_roles (${columnsStr}) VALUES (${placeholders})`;
	const res = SQL.exec('system_sql', query, ...newDataArr);
	let menuRes = true;
	let apiRes = true;
	// role_menu表插入
	if (newData.menu_ids.length && res) {
		let valueStrArr = [];
		const valueArr = [];
		for (i = 0; i < newData.menu_ids.length; i++) {
			valueStrArr.push(`(?,?,?)`);
			valueArr.push(ex.suid().base58(), res, newData.menu_ids[i]);
		}
		menuRes = SQL.exec('system_sql', `INSERT INTO sys_role_menus_rel (rule_id, role_id, menu_id) VALUES ${valueStrArr.join(',')}`, ...valueArr);
	}
	// api权限相关表插入数据
	if (newData.api_ids.length && res) {
		let valueStrArr = [];
		const valueArr = [];
		for (i = 0; i < newData.api_ids.length; i++) {
			valueStrArr.push(`(?,?,?,?,?)`);
			valueArr.push(ex.suid().base58(), newData.role_id, newData.role_key, newData.api_ids[i].method, newData.api_ids[i].path,);
		}
		apiRes = SQL.exec('system_sql', `INSERT INTO casbin_rule (rule_id, role_id, role_key, method, patterns) VALUES ${valueStrArr.join(',')};`, ...valueArr);
	}

	if (res && menuRes && apiRes) {
		return okMsg(res);
	}
	return errMsg(507, '添加失败');
}

function main() {
	// 验证用户权限
	'use api/user/acl/excerpt.js'

	switch (payload.get().method) {
		case 'GET':
			return sql_select();
		case 'PUT':
			return update();
		case 'POST':
			return insert();
		case 'DELETE':
			return sql_delete();
		default:
			response.status.notFound();
			return `404 page not found`;
	}
}
